Home:ALL Converter>How to set up a UNIX domain socket in iOS?

How to set up a UNIX domain socket in iOS?

Ask Time:2019-05-14T23:54:39         Author:zfgo

Json Formatter

I am trying to set up a UNIX domain socket in iOS. According to https://iphonedevwiki.net/index.php/Unix_sockets, this is the code that I used to set up the socket on the server side:

    const char *socket_path = "/var/run/myserver.socket";
    // setup socket
    struct sockaddr_un local;
    strcpy(local.sun_path, socket_path);
    unlink(local.sun_path);
    local.sun_family = AF_UNIX;
    int listenfd = socket(AF_UNIX, SOCK_STREAM, 0);
    printf("listenfd: %d\n", listenfd);
    // start the server
    int r = -1;
    while(r != 0) {
        r = bind(listenfd, (struct sockaddr*)&local, sizeof(local));
        printf("bind: %d\n", r);
        usleep(200 * 1000);
    }
    int one = 1;
    setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    // start listening for new connections
    r = -1;
    while(r != 0) {
        r = listen(listenfd, 20);
        printf("listen: %d\n", r);
        usleep(200 * 1000);
    }
    // wait for new connection, and then process it
    int connfd = -1;
    while(true) {
        if(connfd == -1) {
            // wait for new connection
            connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
            printf("new connfd: %d\n", connfd);
        }
        // process incoming data
        char buffer[4096];
        int len = recv(connfd, buffer, sizeof(buffer), 0);
        if(len == 0) {
            printf("connfd %d disconnected!\n", connfd);
            connfd = -1;
            continue;
        } else {
            printf("connfd %d recieved data: %s", connfd, buffer);
            // send some data back (optional)
            const char *response = "got it!\n";
            send(connfd, response, strlen(response) + 1, 0);
        }
    }

However, when I run this code on my iPhone, I got this in the console:

listenfd: 3
bind: -1
bind: -1
bind: -1
bind: -1
bind: -1
...

It looks like there is a problem when we do bind() as it returns -1, I want to know what I am doing wrong in the code? The errno is 1, which is OPERATION_NOT_PERMITTED

Author:zfgo,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/56134350/how-to-set-up-a-unix-domain-socket-in-ios
yy